package com.xingkeduo.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author chi  2019-01-22 13:22
 **/
public class SqlGenerator {

    private static final Logger logger = LoggerFactory.getLogger(SqlGenerator.class);

    public static void main(String[] args) {
        //实体类po所在的绝对路径
        List<String> s=SqlGenerator.getAllClasses("/Users/xingkeduo/IdeaProjects/xingkeduo_business_comments/src/main/java/com/xingkeduo/pojo/table");

        System.out.println(s);
        for (String className : s) {
//            System.out.println(className);
            if(className.equals("Labels.java")){

                String[] ss=className.split("\\.");
                if(ss.length==2&&(!ss[1].equals("xml"))) {
//
                System.out.println("-- ++++++++++++++++++");
//
                String str= SqlGenerator.generateSql("com.xingkeduo.pojo.table."+ss[0]);
                System.out.println(str);
            }
            }
            //. 必须转译
//            String[] ss=className.split("\\.");
//            //判断防止空指针和xml
//            if(ss.length==2&&(!ss[1].equals("xml"))) {
//
//                System.out.println("-- ++++++++++++++++++");
//
//                String str= SqlGenerator.generateSql("com.xingkeduo.pojo.table."+ss[0]);
//                System.out.println(str);
//            }
        }
    }



    /**
     * 根据实体类生成建表语句
     * @author
     * @date
     * @param className 全类名
     */
    public static String generateSql(String className){
        try {
            Class<?> clz = Class.forName(className);
            className = clz.getSimpleName();
            Field[] fields = clz.getDeclaredFields();


            StringBuffer column = new StringBuffer();
            String varchar = " varchar(255) DEFAULT NULL";
            String intString = " int(4) DEFAULT NULL";
            String dateTimeString = " timestamp(0) NOT NULL DEFAULT '0000-00-00 00:00:00'";
            String dateString = " datetime(0) DEFAULT NULL";
            String enumString = " int(3) DEFAULT NULL";

            for (Field field : fields) {
                column.append(humpToUnderline(field.getName()));

                Class<?> type = field.getType();
                if(type == int.class || type == Integer.class || type == BigDecimal.class){
                    column.append(intString);
                } else if (type == Date.class || type == LocalDateTime.class){
                    column.append(dateTimeString);
                } else if (type == LocalDate.class){
                    column.append(dateString);
                } else if (type.isEnum()){
                    column.append(enumString);
                }
                else {
                    column.append(varchar);
                }

                boolean tableAnnotations = field.isAnnotationPresent(TableAnnotations.class);
                if(tableAnnotations){
                    TableAnnotations fieldAnno = field.getAnnotation(TableAnnotations.class);
                    String value = fieldAnno.value();
                    column.append(" COMMENT '").append(value).append("'");
                }

                column.append(",");
            }

            StringBuffer sql = new StringBuffer();

            sql.append("DROP TABLE IF EXISTS t_"+humpToUnderline(className) +";");

            sql.append(" \n CREATE TABLE t_"+ humpToUnderline(className)   +"(\n")
                    .append("id      BIGINT (20) NOT NULL auto_increment COMMENT '主键ID',")
                    .append("`code` bigint(20)  COMMENT '编码',\n" +
                            "  `version` int(11) NOT NULL DEFAULT 0 COMMENT '乐观锁版本号',\n" +
                            "  `created_by` bigint(20)  COMMENT '创建人ID',\n" +
                            "  `created_time` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '创建时间',\n" +
                            "  `updated_by` bigint(20)  COMMENT '修改人ID',\n" +
                            "  `updated_time` timestamp(0) NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT '修改时间',")
                    .append("\n\n "+column)
                    .append("\n PRIMARY KEY (`id`) USING BTREE")
                    .append("\n\n )ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Compact; ");
            return sql.toString();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            logger.debug("该类未找到！");
            return null;
        }

    }

    /**
     * 获取包下的所有类名称,获取的结果类似于 XXX.java
     * @author
     * @date
     * @param packageName
     * @return
     */
    public static List<String> getAllClasses(String packageName){
        List<String> classList = new ArrayList<String>();
        String className="";
        File f = new File(packageName);
        if(f.exists() && f.isDirectory()){
            File[] files = f.listFiles();
            for (File file : files) {
                className = file.getName();
                classList.add(className);
            }
            return classList;
        }else{
            logger.debug("包路径未找到！");
            return null;
        }
    }

    /**
     * 驼峰转下划线
     * @param para
     * @return
     */
    public static String humpToUnderline(String para){
        StringBuilder sb=new StringBuilder(para);
        int temp=0;//定位
        if (!para.contains("_")) {
            for(int i=0;i<para.length();i++){
                if(Character.isUpperCase(para.charAt(i))  && i!=0){
                    sb.insert(i+temp, "_");
                    temp+=1;
                }
            }
        }
        return sb.toString().toLowerCase();
    }



}